<?php
namespace app\controller;
use app\model\WxGroup;
use think\facade\Db;
class QywxApi{
    // 新建群
    public function add_qywx_group($data){
        if(count(explode(',',$data['userlist'])) < 2){
            return '群成员至少需要2位。';
        }
        if(empty($data['channel_ids'])){
            return '端口不能为空';
        }
        $token = qywx_token();
        $headers = array( 'Content-Type:application/json');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={$token}";
        $da = [
            'name' => $data['name'],
            'owner' => $data['owner'],
            'userlist' => explode(',',$data['userlist']),
        ];
        try {
            $res = http_post($url, $da,'',$headers);
            $res = json_decode($res,true);
            if($res['errcode'] == 0){
                $data['chatid'] = $res['chatid'];
                $data['media_id'] = session('uid');
                $rs = WxGroup::create($data);
                $id = $rs->id;
                $str = '"'.$data['name'].'" 群聊，创建成功。';
                $this->push_message($res['chatid'],$str);
                return true;
            }else{
                return $res['errmsg'];
            } 
        } catch (\Throwable $th) {
            //throw $th;
            return $th->getMessage();
        }
        
        
    }

    // 推送消息
    public function push_message($chatid,$str,$recharge_id=0){
        // $rs = WxGroup::where('id',$groupid)->find();
        
        $token = qywx_token();
        $headers = array('Content-Type:application/json');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={$token}&debug=1";
        $data = [
            'chatid' => $chatid,
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => $str
            ]
        ];
        try {
            $res = http_post($url, $data,'',$headers);
            $res = json_decode($res,true);
            if($res['errcode'] == 0){
                $this->record_wxgroup_msg($str,$recharge_id,$chatid);
                return true;
            }else{
                $this->record_wxgroup_msg($str,$recharge_id,$chatid,0);
                return $res['errmsg'];
            }
            
        } catch (\Throwable $th) {
            $this->record_wxgroup_msg($str,$recharge_id,$chatid,0);
            //throw $th;
            return $th->getMessage();
        }
    }
    // 添加发送消息记录
    public function record_wxgroup_msg($text,$recharge_id,$chatid,$status=1){
        $data['info'] = $text;
        $data['pid'] = $recharge_id;
        $data['wxgroup_id'] = $chatid;
        $data['status'] = $status;
        $data['operator'] = session('uid');
        $data['create_time'] = time();
        try {
            DB::name('wxgroup_msg_log')->save($data);
            return true;
        } catch (\Throwable $th) {
            //throw $th;
            return $th->getMessage();
        }
        
    }









}